#!/usr/bin/env bash
# header: add, replace, and delete header lines.
# 
# Example usage:
# $ seq 10 | header -a 'values'
# $ seq 10 | header -a 'VALUES' | header -e 'tr "[:upper:]" "[:lower:]"'
# $ seq 10 | header -a 'values' | header -d
# $ seq 10 | header -a 'multi\nline' | header -n 2 -e "paste -sd_"
#
# See also: body (https://github.com/jeroenjanssens/command-line-tools-for-data-science)
#
# Author: http://jeroenjanssens.com

usage () {
cat << EOF
header: add, replace, and delete header lines.

usage: header OPTIONS

OPTIONS:
  -n      Number of lines to consider as header [default: 1]
  -a      Add header
  -r      Replace header
  -e      Apply expression to header
  -d      Delete header
  -h      Show this message

Example usage:
  $ seq 10 | header -a 'values'
  $ seq 10 | header -a 'VALUES' | header -e 'tr "[:upper:]" "[:lower:]"'
  $ seq 10 | header -a 'values' | header -d
  $ seq 10 | header -a 'multi\nline' | header -n 2 -e "paste -sd_"

See also: body
EOF
}

get_header () {
	for i in $(seq $NUMROWS); do
		IFS= read -r LINE
		OLDHEADER="${OLDHEADER}${LINE}\n"
	done
}

print_header () {
	echo -ne "$1"
}

print_body () {
	cat
}

OLDHEADER=
NUMROWS=1

while getopts "dn:ha:r:e:" OPTION
do
	case $OPTION in
		n)
			NUMROWS=$OPTARG
			;;
		a)
			print_header "$OPTARG\n"
			print_body
			exit 0
			;;
		d)
			get_header
			print_body
			exit 0
			;;
		r)
			get_header
			print_header "$OPTARG\n"
			print_body
			exit 0
			;;
		e)
			get_header
			print_header "$(echo -ne $OLDHEADER | eval $OPTARG)\n"
			print_body
			exit 0
			;;
		h)
			usage
			exit 0
			;;
	esac
done

get_header
print_header "${OLDHEADER}"
